package com.wjhs.redispractice.repeatsubmit.utils;

import jakarta.servlet.http.HttpServletRequest;

public class AddrUtil {

    /**
     * 获取请求的远程IP地址。
     *
     * @param request HttpServletRequest对象
     * @return 远程IP地址
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 对于通过多层代理的情况，获取第一个非unknown的有效IP地址
        if (ip != null && ip.contains(",")) {
            String[] ips = ip.split(",");
            for (String ipStr : ips) {
                if (!"unknown".equalsIgnoreCase(ipStr)) {
                    ip = ipStr;
                    break;
                }
            }
        }
        return ip;
    }
}


